const baseURL = '/api'

const requestInterceptor = {
	invoke(options) {
		options.url = baseURL + options.url
		options.timeout = 10000
		options.header = {
			...options.header
		}
		const token = uni.getStorageSync("user-token")
		if(token) {
			options.header.Authorization = token
		}
	}
}

uni.addInterceptor('request', requestInterceptor)

export const http = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success(res) {
				if(res.statusCode >= 200 && res.statusCode < 300) {
					if(res.data.code === 1) {
						resolve(res.data.data)
					} else {
						uni.showToast({
							icon:"none",
							title:res.data?.msg
						})
						reject(res)
					}
				} else if(res.statusCode === 401) {
					uni.setStorageSync("user-token", "")
					uni.setStorageSync("user-profile", "")
					uni.navigateTo({
						url:'/pages/login/login'
					})
					uni.showToast({
						icon:"none",
						title:'401报错'
					})
					reject(res)
				} else {
					uni.showToast({
						icon:"none",
						title:res.data?.msg || '请求错误'
					})
					reject(res)
				}
			},
			fail(err) {
				uni.showToast({
					icon:"none",
					title:'网络错误，换个网络试试'
				})
				reject(err)
			}
		})
	})
}